﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Util.Ini;
using Microsoft.Win32;


namespace svnbox {
    public partial class frmProfile : IForm {

        private string rkAppName = "Svnbox";
        RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);

        private void debug(string s) { System.Diagnostics.Debug.WriteLine("{frmProfile} " + s); }

        private Dictionary<string, string> AvailableLanguages;
        private List<IniFile> AvailableProfils;

        public frmProfile() {

            InitializeComponent();

            FormControls.Add(this);

            FormControls.Add(this.btnActiveTab0);
            FormControls.Add(this.btnActiveTab1);
            FormControls.Add(this.btnActiveTab2);
            FormControls.Add(this.btnActiveTab3);
            FormControls.Add(this.btnTest);
            FormControls.Add(this.tabGeneral);
            FormControls.Add(this.grpGeneralChecks);
            FormControls.Add(this.cbMonitorLoad);
            FormControls.Add(this.cbDesktopNotification);
            FormControls.Add(this.cbStartupLoad);
            FormControls.Add(this.grpGlobalLang);
            FormControls.Add(this.tabSettings);
            FormControls.Add(this.grpSettingsSvn);
            FormControls.Add(this.lblPassword);
            FormControls.Add(this.lblUsername);
            FormControls.Add(this.grpSettingsWc);
            FormControls.Add(this.btnSelectWorkingCopy);
            FormControls.Add(this.tabProfile);
            FormControls.Add(this.grpProfileNew);
            FormControls.Add(this.btnSaveProfil);
            FormControls.Add(this.grpProfileLoad);
            FormControls.Add(this.btnLoadProfil);
            FormControls.Add(this.btnCancel);
            FormControls.Add(this.btnSave);
            FormControls.Add(this.btnExit);
            FormControls.Add(this.btnChangeLanguage);

            App.Resource.Translate(this);
        }
        private void onFormLoad(object sender, EventArgs e) {
            btnActiveTab0_Click(null, null);
            SetFormAsProfile();
            if (rkApp.GetValue(rkAppName) == null) {
                cbStartupLoad.Checked = false;
            } else {
                cbStartupLoad.Checked = true;
            }
        }

        private void SetFormAsProfile() {

            txtWorkingCopyPath.Text = App.Profile.Get("wc", "path");
            txtSvnRepository.Text = App.Profile.Get("svn", "repository");
            txtSvnUser.Text = App.Profile.Get("svn", "user");
            txtSvnPassword.Text = App.Profile.Get("svn", "password");

            cbMonitorLoad.Checked =  App.Profile.Get("global", "startupmonitor") == "1" ;
            cbDesktopNotification.Checked = App.Profile.Get("global", "desktopnotif") == "1";

            LoadListProfile();
            LoadListLanguage();
        }

        private void LoadListProfile() {
            cmbProfil.Text = "";
            cmbProfil.Items.Clear();
            AvailableProfils = App.Profile.GetAvailableProfiles();
            foreach (IniFile profil in AvailableProfils) {
                cmbProfil.Items.Add(profil.GetValue("global", "name", "--"));
                if (App.Profile.Get("global", "name") == profil.GetValue("global", "name", "*****")) {
                    cmbProfil.SelectedIndex = cmbProfil.Items.Count - 1;
                }
            }
        }

        private void LoadListLanguage() {
            cmbLang.Text = "";
            cmbLang.Items.Clear();
            AvailableLanguages = App.Resource.GetAvailableLanguages();
            foreach (KeyValuePair<string, string> Lang in AvailableLanguages) {
                cmbLang.Items.Add(Lang.Value);
                if (App.Profile.Get("global", "language") == Lang.Key) {
                    cmbLang.SelectedIndex = cmbLang.Items.Count - 1;
                }
            }
        }

        private void SetProfileAsForm() {
            App.Profile.Set("wc", "path", txtWorkingCopyPath.Text);
            App.Profile.Set("svn", "repository", txtSvnRepository.Text);
            App.Profile.Set("svn", "user", txtSvnUser.Text);
            App.Profile.Set("svn", "password", txtSvnPassword.Text);
            App.Profile.Set("global", "startupmonitor", cbMonitorLoad.Checked ? "1" : "0" );
            App.Profile.Set("global", "desktopnotif", cbDesktopNotification.Checked ? "1" : "0");
        }

        private void btnSelectWC_Click(object sender, EventArgs e) {
            DialogResult fb = FolderBrowserDialog.ShowDialog();
            if (fb == DialogResult.OK && FolderBrowserDialog.SelectedPath != "") {
                txtWorkingCopyPath.Text = FolderBrowserDialog.SelectedPath;
            }
        }
        private bool ValidateSettings() {
            string ErrorMessage = "";
            if (txtSvnUser.Text.Length < 2) {
                ErrorMessage += App.Resource.Lang(this.Name, "MessageInvalidUser", "Invalid username") + "\r\n";
            }
            if (!System.IO.Directory.Exists(txtWorkingCopyPath.Text)) {
                ErrorMessage += App.Resource.Lang(this.Name, "MessageInvalidWorkingCopy", "Invalid working path") + "\r\n";
            } else {
                if (!Svn.CheckWcUri(txtWorkingCopyPath.Text, txtSvnRepository.Text)) {
                    if (MessageBox.Show(App.Resource.Lang(this.Name, "MessageUsePathUri"
                        ,"Selected path contains svn address you wan't to replace entered svn address ?"), "Confirm repository"
                        , MessageBoxButtons.YesNo) == DialogResult.Yes) {
                        txtSvnRepository.Text = Svn.GetUriFromWC(txtWorkingCopyPath.Text);
                    } else {
                        ErrorMessage += App.Resource.Lang(this.Name, "MessageConfigExist", "The path has diffrent svn repository") + "\r\n";
                    }
                }
            }
            Svn SvnChecker = new Svn();
            SvnChecker.CheckAuthentication(txtSvnRepository.Text, txtSvnUser.Text, txtSvnPassword.Text);
            App.MainForm.SetTrayIcon(2);
            SvnChecker.OnAuthStatusChange += delegate {
                if (!SvnChecker.IsAuthentication) {
                    App.MainForm.BalloonTipWarning(App.Resource.Lang(this.Name, "MessageInvalidRepository", "Could not connect to svn check address username or password"));
                }
            };
            if (ErrorMessage == "") {
                return true;
            }
            MessageBox.Show(ErrorMessage);
            return false;
        }

        private void btnSave_Click(object sender, EventArgs e) {
            App.Stop();
            if (ValidateSettings()) {
                SetProfileAsForm();
                App.Start();
                this.Visible = false;
            }
        }

        private void btnCancel_Click(object sender, EventArgs e) {
            this.Visible = false;
        }

        private void btnTest_Click(object sender, EventArgs e) {
            App.MainForm.mLogger_Click(null, null);
        }

        private void btnExit_Click(object sender, EventArgs e) {
            App.MainForm.mExit_Click(null, null);
        }

        private void btnSaveProfil_Click(object sender, EventArgs e) {
            if (ValidateSettings()){
                if (txtNewProfil.Text != "") {
                    string pName = Util.Tools.ArrangeProfileName(txtNewProfil.Text);
                    App.Profile.CreateNewProfile(pName);
                    txtNewProfil.Text = "";
                    cmbProfil.Items.Add(pName);
                    cmbProfil.SelectedIndex = cmbProfil.Items.Count - 1;
                } else {
                    MessageBox.Show(App.Resource.Lang(this.Name, "MessageInvalidProfilName", "Invalid profil name"));
                }
          }
        }

        private void Hide(object sender, FormClosingEventArgs e) {
            if (e.CloseReason == CloseReason.UserClosing) {
                e.Cancel = true;
                this.Visible = false;
            }
        }

        private void btnLoadProfil_Click(object sender, EventArgs e) {

            App.Stop();

            AvailableProfils = App.Profile.GetAvailableProfiles();
            foreach (IniFile profil in AvailableProfils) {
                if (profil.GetValue("global", "name", "--") == cmbProfil.Text) {
                    App.Profile.ini = profil;
                    App.Profile.Set("global", "selected", "1");
                    SetFormAsProfile();
                    App.Resource.ChangeLanguage( App.Profile.Get("global", "language") );
                    
                } else {
                    profil.SetValue("global", "selected", "0");
                }
            }
        }

        private void btnChangeLanguage_Click(object sender, EventArgs e) {
            foreach (KeyValuePair<string, string> lang in AvailableLanguages) {
                if (lang.Value == cmbLang.Text) {
                    App.Resource.ChangeLanguage(lang.Key);
                    break;
                }
            }
        }

        private void cbMonitorLoad_CheckedChanged(object sender, EventArgs e) {
            if (cbMonitorLoad.Checked) {
                App.Profile.Set("global", "startupmonitor", "1");
            }else{
                App.Profile.Set("global", "startupmonitor", "0");
            }
        }

        private void cbDesktopNotification_CheckedChanged(object sender, EventArgs e) {
            if (cbDesktopNotification.Checked) {
                App.Profile.Set("global", "desktopnotif", "1");
            } else {
                App.Profile.Set("global", "desktopnotif", "0");
            }
        }

        private void cbStartupLoad_CheckedChanged(object sender, EventArgs e) {
            if (cbStartupLoad.Checked) {
                rkApp.SetValue(rkAppName, Application.ExecutablePath.ToString());
            } else {
                rkApp.DeleteValue(rkAppName, false);
            }
        }

        private string cmbProfilSelectedValue = null;

        private void cmbProfil_SelectedIndexChanged(object sender, EventArgs e) {
            btnRenameProfil.Enabled = false;
            cmbProfilSelectedValue = cmbProfil.Text;
        }

        private void cmbProfil_TextChanged(object sender, EventArgs e) {
            btnRenameProfil.Enabled = true;
        }

        private void btnRenameProfil_Click(object sender, EventArgs e) {
            AvailableProfils = App.Profile.GetAvailableProfiles();
            foreach (IniFile profil in AvailableProfils) {
                if (profil.GetValue("global", "name", "--") == cmbProfilSelectedValue) {
                    profil.SetValue("global", "name", cmbProfil.Text);
                    break ;
                }
            }
            LoadListProfile();
            btnRenameProfil.Enabled = false;
        }

        private void btnDeleteProfil_Click(object sender, EventArgs e) {
            string ProfileToDelete = "";
            foreach (IniFile profil in AvailableProfils) {
                if (profil.GetValue("global", "name", "--") == cmbProfilSelectedValue) {
                    ProfileToDelete = profil._path;
                    break;
                }
            }
            if (ProfileToDelete != "") {
                try {
                    System.IO.File.Delete(ProfileToDelete);
                } catch (Exception ex) {
                    MessageBox.Show("Deleting profile error " + ex.Message);
                } 
            }
            LoadListProfile();
        }

        private void desactive_btn(Button btn) {
            btn.FlatAppearance.BorderColor = System.Drawing.Color.WhiteSmoke;
            btn.BackColor = System.Drawing.Color.White;
            btn.FlatAppearance.MouseOverBackColor = System.Drawing.Color.MintCream;
            btn.FlatAppearance.MouseDownBackColor = System.Drawing.Color.MintCream;
        }
        private void active_btn(Button btn) {
            btn.BackColor = System.Drawing.Color.MintCream;
            btn.FlatAppearance.BorderColor = System.Drawing.Color.PaleTurquoise;
            btn.FlatAppearance.MouseOverBackColor = System.Drawing.Color.MintCream;
        }

        private void btnActiveTab0_Click(object sender, EventArgs e) {
            active_btn(btnActiveTab0);
            desactive_btn(btnActiveTab1);
            desactive_btn(btnActiveTab2);
            desactive_btn(btnActiveTab3);

            tabsControl.SelectedIndex = 0;

        }
        private void btnActiveTab1_Click(object sender, EventArgs e) {
            desactive_btn(btnActiveTab0);
            active_btn(btnActiveTab1);
            desactive_btn(btnActiveTab2);
            desactive_btn(btnActiveTab3);

            tabsControl.SelectedIndex = 1;
        }
        private void btnActiveTab2_Click(object sender, EventArgs e) {
            desactive_btn(btnActiveTab0);
            desactive_btn(btnActiveTab1);
            active_btn(btnActiveTab2);
            desactive_btn(btnActiveTab3);

            tabsControl.SelectedIndex = 2;
        }
        private void btnActiveTab3_Click(object sender, EventArgs e) {
            desactive_btn(btnActiveTab0);
            desactive_btn(btnActiveTab1);
            desactive_btn(btnActiveTab2);
            active_btn(btnActiveTab3);

            tabsControl.SelectedIndex = 3;
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) {

        }
    }
}
